import { computed, reactive, ref, watch, nextTick } from 'vue';
import { axios } from '@/uni_modules/dx-admin/api/index';

export const useForm = (success: any, modalForm: any, ruleFormRef?: any, onBeforeSubmit?: any) => {
	const layerForm = reactive<{ [key: string]: any }>({});
	const layerRules = reactive<{ [key: string]: any }>({});
	const modelLoading = ref(false);
	//
	const showFormItem = computed(() => (item: any) => {
		if (typeof item.formHide === 'function') {
			return item.formHide(layerForm) !== true;
		}
		return item.formHide !== true;
	});
	// 提交
	const submitForm = async () => {
		if (!ruleFormRef.value) return;
		await ruleFormRef.value.validate((valid: boolean, fields: any) => {
			if (valid) {
				modelLoading.value = true;
				let param = layerForm;
				if (typeof onBeforeSubmit === 'function') {
					let paramForm = onBeforeSubmit(modalForm.type, layerForm);
					if (paramForm === false) {
						modelLoading.value = false;
						return;
					}
					if (!!paramForm) param = paramForm;
				}
				// 去请求
				axios
					.send(modalForm.urls[modalForm.type], modalForm.funcName || 'dx-func-admin', param)
					.then(({ code, message }) => {
						if (code === 1000) {
							success();
						} else {
							ElMessage.error(message);
						}
					})
					.catch(() => {
						ElMessage.error('操作失败！');
					})
					.finally(() => {
						modelLoading.value = false;
					});
			}
		});
	};
	// 设置表单 + 规则
	const setFormField = (fields: any) => {
		fields.map((item: any) => {
			layerRules[item.field] = item.rules;
			layerForm[item.field] = item?.value;
			// 监听表单字段值
			if (typeof item.watch === 'function') {
				watch(
					() => layerForm[item.field],
					(newVal, oldVal) => {
						item.watch(newVal, oldVal, layerForm);
					}
				);
			}
		});
	};
	// 设置字段值
	const setFormItem = (field: string, value: any) => {
		if (field.includes('.')) {
			let arr = field.split('.');
			switch (arr.length) {
				case 2:
					layerForm[arr[0]][arr[1]] = value;
					break;
				case 3:
					layerForm[arr[0]][arr[1]][arr[2]] = value;
					break;
				case 4:
					layerForm[arr[0]][arr[1]][arr[2]][arr[3]] = value;
					break;
			}
		} else {
			layerForm[field] = value;
		}
	};
	// 设置值
	const renderFormValue = () => {
		if (modalForm.type === 'edit') {
			nextTick(() => {
				modalForm.fields.map((item: any) => {
					setFormItem(item.field, item.edit !== void 0 ? item.edit : modalForm?.row[item.field]);
				});
				setFormItem('_id', modalForm.row._id);
			});
		} else {
			nextTick(() => {
				ruleFormRef.value?.resetFields();
				// 默认值，覆盖
				if (typeof modalForm?.row === 'object') {
					for (let key of Object.keys(modalForm.row)) {
						setFormItem(key, modalForm.row[key]);
					}
				}
			});
		}
	};

	return {
		setFormField,
		showFormItem,
		layerForm,
		layerRules,
		submitForm,
		modelLoading,
		setFormItem,
        renderFormValue
	};
};
